#region File Description
//  XAEnima 
//  License: GNU/GPL
//  Developer: Federico Leonardo Motta
//  File description: This Screen is used to choose users frequencies
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using XAEnima.Core.GameManager;
using XAEnima.Core.Stimulation.Tipi;
using XAEnima.Core.Stimulation.External;
using SharedContent;
#endregion

namespace XAEnima.Core.Screens.Test
{
    public delegate void TestAction();
    public class Screening : Microsoft.Xna.Framework.DrawableGameComponent
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        bool OldState = false;
        float screenscale;
        Rectangle area;
        Matrix SpriteScale;
        IInputManager InputManagerService;
        StimulationManager sm;
        IComunicationManager sender;
        SpriteFont font;
        Texture2D current, left, right, up, down, center;
        List<Vector2> posizioni;
        Vector2 pos = new Vector2();
        /* Frequenze */
        Int16[] Values = { 43, 37, 32, 28, 26, 23, 21, 20, 18, 17, 16, 15 };
        int index = 0;
        Boolean stim = false, isFirstime = true;
        float time = 0;
        

        public event TestAction OnBack;

        public Screening(Game game)
            : base(game)
        {
            graphics = StateManager.graphic;
            InputManagerService = (IInputManager)Game.Services.GetService(typeof(IInputManager));
            InputManagerService.SPressed += new PressedEventHandler(SIsPressed);
            InputManagerService.SReleased += new PressedEventHandler(SIsReleased);
            InputManagerService.XPressed += new PressedEventHandler(XIsPressed);
            
            sm = new StimulationManager(Game);
            posizioni = new List<Vector2>();
        }

        public override void Initialize()
        {
            screenscale = (float)(Game.GraphicsDevice.Viewport.Width / 1600f);
            spriteBatch = (Game.Services.GetService(typeof(SharedContext)) as SharedContext).sprite_batch;
            sender = (IComunicationManager)Game.Services.GetService(typeof(IComunicationManager));
            area = Game.GraphicsDevice.Viewport.TitleSafeArea;
            Game.IsFixedTimeStep = true;
            Game.TargetElapsedTime = TimeSpan.FromSeconds(1.0 / 60);
            font = Game.Content.Load<SpriteFont>(@"Arial");
            left = Game.Content.Load<Texture2D>(@"Screens/Test/freccia_l");
            right = Game.Content.Load<Texture2D>(@"Screens/Test/freccia_r");
            up = Game.Content.Load<Texture2D>(@"Screens/Test/freccia_u");
            down = Game.Content.Load<Texture2D>(@"Screens/Test/freccia_d");
            center = Game.Content.Load<Texture2D>(@"Screens/Test/portal");
            posizioni.Add(new Vector2(160, (StateManager.graphic.PreferredBackBufferHeight / 2) - left.Height * screenscale / 2));
            posizioni.Add(new Vector2(StateManager.graphic.PreferredBackBufferWidth - (160 + right.Width * screenscale), (StateManager.graphic.PreferredBackBufferHeight / 2) - right.Height * screenscale / 2));
            posizioni.Add(new Vector2((StateManager.graphic.PreferredBackBufferWidth / 2) - up.Width * screenscale / 2, 160));
            posizioni.Add(new Vector2((StateManager.graphic.PreferredBackBufferWidth / 2) - up.Width * screenscale / 2, StateManager.graphic.PreferredBackBufferHeight - (160 + down.Height * screenscale)));
            posizioni.Add(new Vector2(StateManager.graphic.PreferredBackBufferWidth / 2 - center.Width * screenscale / 2, StateManager.graphic.PreferredBackBufferHeight / 2 - center.Height * screenscale / 2));
            current = center;
            pos = posizioni.ElementAt(4);
            sm.Init();
            base.Initialize();
        }

        protected override void LoadContent()
        {
            float screenscale = (float)graphics.GraphicsDevice.Viewport.Width / 800f;
            SpriteScale = Matrix.CreateScale(screenscale, screenscale, 1);
        }

        public override void Update(GameTime gameTime)
        {
            if (OldState)
            {
                time += (float)gameTime.ElapsedGameTime.Milliseconds;
                if (isFirstime && time > 600f)
                {
                    sender.HIMStartAcquisition();
                    isFirstime = false;
                    time = 7500f;
                }
                else if ((!isFirstime) && (time >= 8000f))
                {
                    if (stim && (index < 12))
                    {
                        sender.HIMScreening(Values[index]);
                        current = up;
                        pos = posizioni.ElementAt(2);
                        sm.SetFrequencies(9999, 9999, Values[index], 9999);
                        sm.Start();
                        index++;
                    }
                    else
                    {
                        sender.HIMScreening(1);
                        current = center;
                        pos = posizioni.ElementAt(4);
                        sm.SetFrequencies(0, 0, 0, 0);
                        sm.Stop();
                    }
                    if (index == 12)
                    {
                        sender.HIMScreening(0);
                        sm.Stop();
                        sm.Close();
                        
                        
                        if (OnBack != null) { OnBack(); }
                    }
                    time = 0;
                    stim = !stim;
                }
            }

            base.Update(gameTime);
        }
        protected override void Dispose(bool disposing)
        {
            Game.Content.Unload();
            Game.Services.RemoveService(typeof(Test));
            base.Dispose(disposing);
        }

        public void Detach()
        {
            // Detach the event and delete the list
            InputManagerService.EnterPressed -= new PressedEventHandler(SIsPressed);
            InputManagerService.SReleased -= new PressedEventHandler(SIsReleased);
            InputManagerService.XPressed -= new PressedEventHandler(XIsPressed);
            InputManagerService = null;
        }

        public override void Draw(GameTime gameTime)
        {
            //graphics.GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();
            SpriteFont c = Game.Content.Load<SpriteFont>("Arial");
            if (OldState == false)
            {
                spriteBatch.DrawString(font, "Premere S per attivare stimolatori",
                   new Vector2(300, 200),
                   Color.Yellow,
                   0.0f,
                   new Vector2(0, 0),
                   screenscale * 1.2f,
                   SpriteEffects.None, 0);

                spriteBatch.DrawString(font, "X per tornare al menu.",
                   new Vector2(400, 320),
                   Color.Red,
                   0.0f,
                   new Vector2(0, 0),
                   screenscale * 1.2f,
                   SpriteEffects.None, 0);
            }
            else
            {
                spriteBatch.Draw(current, pos, null, Color.White, 0f, Vector2.Zero, screenscale, SpriteEffects.None, 0f);

            }
            spriteBatch.End();

            base.Draw(gameTime);
        }

        public void SIsPressed()
        {
            if (OldState)
            {
                sm.Stop();
                index = 12;

            }
            else
            {
                sender.HIMRequestParams();
            }

        }

        public void SIsReleased()
        {
            OldState = !OldState;
        }

        public void XIsPressed()
        {
            sm.Stop();
            sm.Close();
            if (OnBack != null) { OnBack(); }
        }
    }
}
